/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ucjava.chat.commserve.rmi.server;

import com.ucjava.chat.commserve.rmi.common.IChatClientRMI;
import com.ucjava.chat.commserve.rmi.common.Message;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;

/**
 * This class stores info about one connected client: 
 * 1. user name 
 * 2. host from which connected 
 * 3. timestamp of last activity
 *
 * It also stores an RMI stub that the server can use to call methods on this
 * client, and a message queue that stores messages that need to be sent to this
 * client.
 *
 * @author tony
 */
public class LoggedInClient
{

    private String username;
    private Timestamp lastActivity;
    private String host;
    private IChatClientRMI rcvMsgStub;
    private Queue<Message> msgQueue = new LinkedList<Message>();

    public IChatClientRMI getRcvMsgStub()
    {
        return rcvMsgStub;
    }

    public void setRcvMsgStub(IChatClientRMI rcvMsgStub)
    {
        this.rcvMsgStub = rcvMsgStub;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public Timestamp getLastActivity()
    {
        return lastActivity;
    }

    public void setLastActivity(Timestamp lastActivity)
    {
        this.lastActivity = lastActivity;
    }

    public String getHost()
    {
        return host;
    }

    public void setHost(String host)
    {
        this.host = host;
    }

    public Queue<Message> getMsgQueue()
    {
        return this.msgQueue;
    }

    /**
     * Set lastAccessTime to now.
     */
    public void updateAccessTime()
    {
        Date dt = new Date();
        this.setLastActivity(new Timestamp(dt.getTime()));
    }
    
    /**
     * Add one Message to this client's queue.
     * @param msg 
     */
    public void enqueueMessage(Message msg)
    {
        synchronized(this.msgQueue)
          {
            this.msgQueue.add(msg);
          }
    }
    

    /**
     * Loops through this client's message queue and sends all messages. Then
     * empties the queue and updates last access time.
     *
     * This should probably intercept exceptions that occur if the client cannot
     * be reached and return some sort of error code to the caller. Then, the
     * caller could take appropriate action such as logging this client out.
     *
     * @throws RemoteException
     */
    public synchronized void sendMyMessages() throws RemoteException
    {
        for (Message msg : msgQueue)
          {
            rcvMsgStub.receiveMessage(msg);
          }
        msgQueue.clear();
        updateAccessTime();
    }
} // end class LoggedInClient
